package security.auth.config;

import lombok.extern.slf4j.Slf4j;
import security.user.model.SecurityUser;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.google.gson.Gson;

import java.util.*;

@Component
@Slf4j
public class SetAdditionalInfoToTokenConverter extends DefaultUserAuthenticationConverter {

    /**
     * 这个方法把额外的信息添加进jwt token （默认只添加用户名，权限）
     * 这里额外添加了用户id
     * 方法将会在授权服务器起作用
     * @param authentication
     * @return
     */

   @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        Map<String, Object> response = new LinkedHashMap<String, Object>();
       // response.put(USERNAME, authentication.getName());   源码里面的，不知道USERNAME是什么，注释掉吧
       log.info("set additional infos...");
       Object principal = authentication.getPrincipal();
       //不要强制转换principal, 用json转化，不然各种莫名其妙的坑

       Gson gson=new Gson();
       String jsonStr= gson.toJson(principal);
       SecurityUser user=gson.fromJson(jsonStr,SecurityUser.class);

       //加上自定义的用户名和id
       response.put("id", user.getId());
       response.put("username", user.getUsername());
       response.put("email", user.getEmail());
       response.put("mobile", user.getMobile());
       response.put("qq", user.getQq());
       response.put("aliPay", user.getAliPay());
       response.put("weChat", user.getWeChat());

        if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
            response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
        }
        return response;
    }

}
